package com.example.peibei.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dingtao.common.bean.Dynamic;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDFragment;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.ImageViewInfo;
import com.example.peibei.service.presenter.DynamicPresenter;
import com.example.peibei.service.presenter.GiveUpPresenter;
import com.example.peibei.ui.activity.DynamicDetailActivityTwo;
import com.example.peibei.ui.activity.PersonInfoActivityTwo;
import com.example.peibei.ui.adapter.DynamicListAdapter;
import com.example.peibei.ui.weight.ImagePreviewLoader;
import com.previewlibrary.GPreviewBuilder;
import com.previewlibrary.ZoomMediaLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 动态列表
 */
public class DynamicListFragment extends WDFragment {

    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    String categoryId = "";
    private DynamicListAdapter adapter;
    private DynamicPresenter dynamicPresenter;
    private SPUtils spUtils;
    private String token;
    private int updatePosition;
    private GiveUpPresenter giveUpPresenter;
    private List<ImageViewInfo> stringList = new ArrayList<>();

    public DynamicListFragment(String categoryId) {
        this.categoryId = categoryId;
    }

    @Override
    public String getPageName() {
        return "动态列表fragment";
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dynamic_list;
    }

    @Override
    protected void initView() {
        spUtils = new SPUtils(getActivity(), SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        ZoomMediaLoader.getInstance().init(new ImagePreviewLoader());
        //获取数据
        dynamicPresenter = new DynamicPresenter(new OrderCall());
        giveUpPresenter = new GiveUpPresenter(new FollowCall());

        refreshLayout.setOnRefreshListener(refreshLayout -> onRefreshStart());
        refreshLayout.setOnLoadMoreListener(refreshLayout -> onLoadMoreStart());
        onRefreshStart();

        adapter = new DynamicListAdapter("1");
        adapter.addChildClickViewIds(R.id.zan_ly, R.id.iv_head, R.id.iv_img_one, R.id.iv_img_two_dynamic, R.id.iv_img_three, R.id.iv_img_four);
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.zan_ly) {
                    updatePosition = position;
                    Dynamic.RecordsDTO item = (Dynamic.RecordsDTO) adapter.getData().get(position);
                    boolean dianzan = item.isDianzan();
                    long id = item.getId();
                    giveUpPresenter.reqeust(dianzan, "Bearer " + token, id + "");
                } else if (view.getId() == R.id.iv_head) {
                    Dynamic.RecordsDTO order = (Dynamic.RecordsDTO) adapter.getData().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putString("mid", order.getMember().getMid() + "");
                    intent(PersonInfoActivityTwo.class, bundle);
                } else if (view.getId() == R.id.iv_img_one || view.getId() == R.id.iv_img_four) {
                    stringList.clear();
                    Dynamic.RecordsDTO order = (Dynamic.RecordsDTO) adapter.getData().get(position);
                    List<Dynamic.RecordsDTO.ItemDTO> item = order.getItem();
                    loadImages(item, 0);
                } else if (view.getId() == R.id.iv_img_two_dynamic) {
                    stringList.clear();
                    Dynamic.RecordsDTO order = (Dynamic.RecordsDTO) adapter.getData().get(position);
                    List<Dynamic.RecordsDTO.ItemDTO> item = order.getItem();
                    loadImages(item, 1);
                } else if (view.getId() == R.id.iv_img_three) {
                    stringList.clear();
                    Dynamic.RecordsDTO order = (Dynamic.RecordsDTO) adapter.getData().get(position);
                    List<Dynamic.RecordsDTO.ItemDTO> item = order.getItem();
                    loadImages(item, 2);
                }
            }
        });
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Dynamic.RecordsDTO item = (Dynamic.RecordsDTO) adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("subjectId", item.getId() + "");
                bundle.putString("status", "1");
                intent(DynamicDetailActivityTwo.class, bundle);
            }
        });

        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.setAdapter(adapter);
    }

    private void loadImages(List<Dynamic.RecordsDTO.ItemDTO> item, int position) {
        if (item != null && item.size() > 0) {
            for (int i = 0; i < item.size(); i++) {
                if (!TextUtils.isEmpty(item.get(i).getUrl())) {
                    stringList.add(new ImageViewInfo(item.get(i).getUrl()));
                }
            }
            //图片预览（关键
            GPreviewBuilder.from(getActivity())
                    .setData(stringList)  //数据
                    .setCurrentIndex(position)  //图片下标
                    .setSingleFling(true)  //是否在黑屏区域点击返回
                    .setDrag(false)  //是否禁用图片拖拽返回
                    .setType(GPreviewBuilder.IndicatorType.Number)  //指示器类型
                    .start();  //启动
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        token = spUtils.getString(SpConstant.USER_TOKEN);
    }

    public void onRefreshStart() {
        dynamicPresenter.reqeust(true, "1", categoryId, "Bearer " + token);
    }

    public void onLoadMoreStart() {
        if (dynamicPresenter.isRunning()) {
            refreshLayout.finishLoadMore();
            return;
        }
        dynamicPresenter.reqeust(false, "1", categoryId, "Bearer " + token);
    }

    class OrderCall implements DataCall<Dynamic> {

        View view;
        @Override
        public void success(Dynamic data, Object... args) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            //添加列表并刷新
            if (dynamicPresenter.getPage() == 1) {
                adapter.setNewInstance(data.getRecords());
            }else {
                adapter.addData(data.getRecords());
            }
            if (adapter.getData().isEmpty()){
                view = LayoutInflater.from(getContext()).inflate(R.layout.empty_home_child,null,false);
                adapter.setFooterView(view);
            }else {
                if (view != null)
                    adapter.removeFooterView(view);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
    }

    class FollowCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            //还需要刷新处理
//            Dynamic.RecordsDTO recordsDTO = dynamicListAdapter.getData().get(updatePosition);
            Dynamic.RecordsDTO recordsDTO = adapter.getItem(updatePosition);
            int follow = recordsDTO.getFollow();
            boolean dianzan = recordsDTO.isDianzan();
            recordsDTO.setDianzan(!dianzan);
            recordsDTO.setFollow(!dianzan ? follow + 1 : follow - 1);
            adapter.notifyDataSetChanged();
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }


}
